<?php


namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\Address as AddressModel;
/***
 * 地址相关接口
 * Class Address
 * @package app\api\controller
 */
class Address extends Base
{
    /***
     * Desc : 更新收货地址信息
     * User : HAIYUN
     * Date : 2022-01-04 16:09
     */
    public function createOrUpdateAddress(){
        //校验参数
        $rules = [
            ['name', 'require', '10001'],
            ['mobile', 'require|/^1[34578]\d{9}$/', '10001|10002'],
            ['province','require','10001'],
            ['city','require','10001'],
            ['country','require','10001'],
            ['detail','require','10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user = $userModel->where("id",$uid)->find();
        if(!$user){
            $this->return_msg("20004","用户不存在",[]);
        }
        //根据用户地址是否存在，判断是更新还是添加地址
        $addressModel = new AddressModel();
        $user_address = $addressModel->where('user_id',$uid)->find();
        //过滤不必要的参数
        $safe_data = $this->getDataByRule($this->params, $rules);
        $res = false;
        if(!$user_address){
            $safe_data['user_id'] = $uid;
            $res = $addressModel->add($safe_data);
            unset($safe_data['user_id']);
        }else{
           $res = $addressModel->edit($safe_data,['user_id' => $uid]);
        }
        if($res !== false){
            $this->return_msg("00000","编辑地址信息成功",$safe_data);
        }else{
            $this->return_msg("20002","编辑地址信息失败",[]);
        }
    }

    /***
     * Desc :获取用户收货地址信息
     * User : HAIYUN
     * Date : 2022-01-05 14:07
     */
    public function getAddress()
    {
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user = $userModel->where("id",$uid)->find();
        if(!$user){
            $this->return_msg("20004","用户不存在",[]);
        }
        //查看收货地址
        $addressModel = new AddressModel();
        $user_address = $addressModel->where('user_id',$uid)->find();
        $this->return_msg("00000","查询收货地址成功",$user_address);
    }


}